<template>
  <view v-if="!isLogin">
    <uni-card title="用户登录">

      <uni-forms ref="form">
        <uni-forms-item label="用户名">
          <uni-easyinput v-model="userform.username" placeholder="" />
        </uni-forms-item>

        <uni-forms-item label="登录密码">
          <uni-easyinput type="password" v-model="userform.password" placeholder="" />
        </uni-forms-item>

        <uni-forms-item>
          <button type="primary" @click="login">登录</button>
        </uni-forms-item>

        <uni-forms-item>
          <button type="warn">重填</button>
        </uni-forms-item>
      </uni-forms>

    </uni-card>

  </view>
  <view v-else>
    <uni-section :title="userInfo.nickname || user.username" :sub-title="userInfo.info || '空空如也'">
      <template v-slot:decoration>
        <image class="logo" :src="userLogo" mode="aspectFit"></image>
      </template>
    </uni-section>

    <uni-section title="功能" type="line">
      <uni-list>
        <uni-list-item clickable @click="logout" title="安全退出" show-arrow></uni-list-item>
      </uni-list>
    </uni-section>
  </view>
</template>

<script setup>
  /* 
    作业，完成注册功能
    修改我的页面中登录之后的显示信息（添加手机和邮箱等信息显示）
  */
  import {
    ref
  } from 'vue'

  import {
    storeToRefs
  } from 'pinia'

  import {
    Api
  } from '@/js/api.js'

  import {
    useUserStore
  } from '@/stores/user.js'

  const {
    updateUserInfo
  } = useUserStore()

  const {
    isLogin,
    user,
    userInfo,
    userLogo
  } = storeToRefs(useUserStore())

  const userform = ref({
    "username": "",
    "password": ""
  })

  const login = () => {
    uni.showLoading({
      title: '登录中。。。'
    })
    Api.post('/auth', userform.value, (data) => {
      if (data.success) {
        updateUserInfo(() => {
          uni.hideLoading()
          uni.showToast({
            title: '登录成功',
            icon: 'success'
          })
        })
        return
      }
      uni.hideLoading()
      uni.showToast({
        title: data.message,
        icon: 'error'
      })
    })
  }

  const logout = () => {
    uni.showLoading({
      title: '安全退出中。。。'
    })
    Api.delete('/auth', {}, () => {
      updateUserInfo(() => {
        uni.hideLoading()
      })
    })
  }
</script>

<style>
  .logo {
    width: 3rem !important;
    height: 3rem !important;
    border-radius: 50%;
    display: block;
    margin-right: 1rem;
  }
</style>